package com.imut.lagain.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.imut.lagain.entity.User;
import com.imut.lagain.service.IUserService;
import com.imut.lagain.util.JwtUtil;
import com.imut.lagain.util.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/users")
@RequiredArgsConstructor
@Validated
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    private final IUserService userService;
    private final JwtUtil jwtUtil;

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ResponseEntity<Map<String, Object>> getCurrentUser(
            @RequestHeader("Authorization") String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            User user = userService.getById(userId);
            if (user != null) {
                response.put("success", true);
                response.put("data", user);
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
        } catch (Exception e) {
            log.error("获取当前用户信息失败", e);
            response.put("success", false);
            response.put("message", "获取用户信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取当前用户信息 (兼容/profile路径)
     */
    @GetMapping("/profile")
    public ResponseEntity<Map<String, Object>> getProfile(
            @RequestHeader("Authorization") String authorization) {
        return getCurrentUser(authorization);
    }

    /**
     * 更新当前用户信息
     */
    @PutMapping("/profile")
    public ResponseEntity<Map<String, Object>> updateProfile(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody UserUpdateRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long currentUserId = jwtUtil.getUserIdFromToken(token);
            
            User user = userService.getById(currentUserId);
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 更新用户信息
            user.setNickname(request.getNickname());
            user.setAvatarUrl(request.getAvatarUrl());
            user.setUpdateTime(java.time.LocalDateTime.now());
            
            boolean success = userService.updateById(user);
            if (success) {
                response.put("success", true);
                response.put("data", user);
                response.put("message", "用户信息更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "更新用户信息失败");
                return ResponseEntity.internalServerError().body(response);
            }
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            response.put("success", false);
            response.put("message", "更新用户信息失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新用户密码
     */
    @PutMapping("/password")
    public ResponseEntity<Map<String, Object>> updatePassword(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody PasswordUpdateRequest request) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long currentUserId = jwtUtil.getUserIdFromToken(token);
            
            User user = userService.getById(currentUserId);
            if (user == null) {
                response.put("success", false);
                response.put("message", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 验证旧密码
            if (!ValidationUtil.validatePassword(request.getOldPassword(), user.getPassword())) {
                response.put("success", false);
                response.put("message", "旧密码不正确");
                return ResponseEntity.badRequest().body(response);
            }
            
            // 更新密码
            user.setPassword(ValidationUtil.encodePassword(request.getNewPassword()));
            user.setUpdateTime(java.time.LocalDateTime.now());
            
            boolean success = userService.updateById(user);
            if (success) {
                response.put("success", true);
                response.put("message", "密码更新成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "更新密码失败");
                return ResponseEntity.internalServerError().body(response);
            }
        } catch (Exception e) {
            log.error("更新密码失败", e);
            response.put("success", false);
            response.put("message", "更新密码失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取用户统计数据
     */
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getStats(
            @RequestHeader("Authorization") String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long currentUserId = jwtUtil.getUserIdFromToken(token);
            
            if (currentUserId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            Map<String, Object> stats = userService.getUserStats(currentUserId);
            response.put("success", true);
            response.put("data", stats);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户统计数据失败", e);
            response.put("success", false);
            response.put("message", "获取统计数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取用户设置
     */
    @GetMapping("/settings")
    public ResponseEntity<Map<String, Object>> getSettings(
            @RequestHeader("Authorization") String authorization) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long currentUserId = jwtUtil.getUserIdFromToken(token);
            
            if (currentUserId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 这里应该从数据库获取用户设置，暂时返回默认设置
            Map<String, Object> settings = new HashMap<>();
            settings.put("notifications", true);
            settings.put("privacy", "public");
            settings.put("theme", "light");
            
            response.put("success", true);
            response.put("data", settings);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取用户设置失败", e);
            response.put("success", false);
            response.put("message", "获取设置失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 更新用户设置
     */
    @PutMapping("/settings")
    public ResponseEntity<Map<String, Object>> updateSettings(
            @RequestHeader("Authorization") String authorization,
            @RequestBody Map<String, Object> settings) {
        Map<String, Object> response = new HashMap<>();
        
        try {
            String token = authorization.replace("Bearer ", "");
            Long currentUserId = jwtUtil.getUserIdFromToken(token);
            
            if (currentUserId == null) {
                response.put("success", false);
                response.put("message", "无效的用户令牌");
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
            }
            
            // 这里应该将设置保存到数据库，暂时只是模拟
            log.info("用户 {} 更新设置: {}", currentUserId, settings);
            
            response.put("success", true);
            response.put("message", "设置更新成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("更新用户设置失败", e);
            response.put("success", false);
            response.put("message", "更新设置失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 用户信息更新请求
     */
    public static class UserUpdateRequest {
        @Size(max = 50, message = "昵称长度不能超过50个字符")
        private String nickname;
        
        @Size(max = 500, message = "头像URL长度不能超过500个字符")
        private String avatarUrl;
        
        @Size(max = 200, message = "个性签名长度不能超过200个字符")
        private String bio;
        
        private Integer gender;
        
        @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
        private String phone;
        
        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
        
        public String getAvatarUrl() { return avatarUrl; }
        public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; }
        
        public String getBio() { return bio; }
        public void setBio(String bio) { this.bio = bio; }
        
        public Integer getGender() { return gender; }
        public void setGender(Integer gender) { this.gender = gender; }
        
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
    }

    /**
     * 密码更新请求
     */
    public static class PasswordUpdateRequest {
        @NotBlank(message = "旧密码不能为空")
        @Size(min = 6, max = 20, message = "密码长度必须在6-20个字符之间")
        private String oldPassword;
        
        @NotBlank(message = "新密码不能为空")
        @Size(min = 6, max = 20, message = "密码长度必须在6-20个字符之间")
        private String newPassword;
        
        public String getOldPassword() { return oldPassword; }
        public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; }
        
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }
}